import requestConfig from "@/uni_modules/uniapp-kantboot/libs/config/requestConfig";
import request from "@/uni_modules/uniapp-kantboot/libs/request";
import event from "@/uni_modules/uniapp-kantboot/libs/event";

function generateMemory() {
    return new Promise((resolve, reject) => {
        request.send({
            uri: "/middleground-common-web/tokenMemory/generateMemory",
            stateSuccess: (res) => {
                resolve(res.data);
            },
            stateFail: (res) => {
                reject(res.data);
            }
        });
    });
}

function start() {
    connectWebSocket();

    event.on("login:success",(res)=>{
        closeWebSocket();
        setTimeout(()=>{
            connectWebSocket();
        },500);
    });

}

/**
 * 连接WebSocket
 */
let  connectWebSocket = async ()=> {

    let memory = "";
    await generateMemory().then((res) => {
        memory = res;
    }).catch((res) => {
        console.error(res);
    });
    // 如果没有记忆体，就断开
    if(!memory){
        return;
    }


    uni.connectSocket({
        url: `${requestConfig.rootWebSocketAddressList}/${memory}`, // 你的WebSocket服务器地址
        complete: (res) => {
            console.log('连接结果', res);
        }
    });


    let heartbeatInterval = setInterval(()=>{
        sendMessage({
            operateCode:"heartbeat"
        });
    },5000);

    // 监听WebSocket事件
    uni.onSocketOpen((res) => {
        console.log('WebSocket连接已打开！', res);
    });
    uni.onSocketError((res) => {
        console.log('WebSocket连接打开失败，请检查！', res);
        try{
            clearInterval(heartbeatInterval);
        }catch (e) {
        }
        setTimeout(()=>{
            connectWebSocket();
        },2000);
    });
    uni.onSocketMessage((res) => {
        console.log('收到服务器内容：', res.data);
        // operateCode:"heartbeat"
        let json = JSON.parse(res.data);
        uni.$emit(json.emit,json);
    });
    uni.onSocketClose((res) => {
        console.log('WebSocket已关闭！', res);
        try{
            clearInterval(heartbeatInterval);
        }catch (e) {
        }
        setTimeout(()=>{
            connectWebSocket();
        },2000);
    });

}

// 发送消息
function sendMessage(message) {
    uni.sendSocketMessage({
        data: JSON.stringify(message),
        success: (res) => {
            console.log('发送成功', res);
        },
        fail: (res) => {
            console.log('发送失败', res);
        }
    });
}

// 关闭WebSocket连接
function closeWebSocket() {
    uni.closeSocket();
}

export default {
    connectWebSocket,
    sendMessage,
    closeWebSocket
}
